package com.action.service.pressenter;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.action.childbase.ChildBasePressent;
import com.action.entity.UserCommentVO;
import com.action.entity.XyBUserRecvRed;
import com.action.entity.UserRedpacket;
import com.action.service.ChildRestServer;
import com.action.ui.activity.OpenPacketActivity;
import com.base.app_core.base.ActionPacketView;
import com.base.app_core.base.BaseView;
import com.base.app_core.model.Paginated;
import com.base.app_core.model.dto.Advertiser;
import com.base.app_core.service.Retrofit.RestServer;
import com.base.app_core.service.rx.Callback;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.XYBAUtils;
import com.base.app_core.util.DateUtil;
import com.base.app_core.util.log.F;
import com.blankj.utilcode.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * Created by jiansheng.li on 2018/3/31.
 */

public class RedpakcetPressenter extends ChildBasePressent<BaseView> {

    private int mTick = AppConstants.DEFAULT_AD_TIME;
    private int mViewTick = AppConstants.DEFAULT_VIEW_TIME;

    @Inject
    public RedpakcetPressenter(ChildRestServer mRestfull, RestServer server) {
        super(mRestfull, server);
    }

    //获取红包详情
    public void fetchRedpacketDetail(String sn) {
        Map<String, Object> map = new HashMap<>();
        map.put(AppConstants.FIELD.SN, sn);
        invoke(mChildRest.fetchRedPacketDetail(map), new Callback<XyBUserRecvRed>());
    }

    //获取领取红包列表
    public void fetchRedUserList(int pageNo, String sn) {
        Map<String, Object> map = new HashMap<>();
        map.put(AppConstants.FIELD.PAGE, pageNo);
        map.put(AppConstants.FIELD.PAGESIZE, AppConstants.Const.PAGESIZE);
        map.put(AppConstants.FIELD.SN, sn);
        invoke(mChildRest.fetchRedUserList(map), new Callback<List<UserRedpacket>>());
    }

    //提交评价
    public void postComment(String comment, String sn) {
        Map<String, Object> map = new HashMap<>();
        map.put(AppConstants.FIELD.COMMENTCONTENT, comment);
        map.put(AppConstants.FIELD.SN, sn);
        invoke(mChildRest.postComment(map), new Callback<Map>() {
            @Override
            public void onResponse(Map data, Paginated paginated,Object extraData) {
                super.onResponse(data, paginated,extraData);
                F.j("评论成功");
                if (isnotNull() && mLifecycle.get() instanceof ActionPacketView.onPostComment) {
                    ((ActionPacketView.onPostComment) mLifecycle.get()).onCommentSuccess();
                }
            }
        });
    }

    //获取评论列表
    public void fetchCommentList(String sn, int pageNo) {
        Map<String, Object> map = new HashMap<>();
        map.put(AppConstants.FIELD.SN, sn);
        map.put(AppConstants.FIELD.PAGE, pageNo);
        map.put(AppConstants.FIELD.PAGESIZE, AppConstants.Const.PAGESIZE);
        invoke(mChildRest.fetchCommentList(map), new Callback<List<UserCommentVO>>() {
            @Override
            public void onResponse(List<UserCommentVO> data, Paginated paginated,Object extraData) {
                if (isnotNull()) {
                    if (XYBAUtils.isEmpty(data)) {
                        mLifecycle.get().notifyData(new ArrayList<UserCommentVO>(), UserCommentVO.class, paginated);
                    } else {
                        super.onResponse(data, paginated,extraData);
                    }
                }
            }
        });
    }


    public void indexGetAdvertiseInfo(Integer miType) {
        Map<String, Object> map = new HashMap<>();
        map.put(AppConstants.FIELD.AD_TYPE, miType);
        invoke(mRestfull.indexGetAdvertiseInfo(map), new Callback<List<Advertiser>>() {
            @Override
            public void onResponse(List<Advertiser> data, Paginated paginated,Object extraData) {
                super.onResponse(data, paginated,extraData);
            }
        });
    }

    //打开红包业务
    public void openRedPacket(final String sn, final String psw, final Integer type) {
        Map<String, Object> map = new HashMap<>();
        map.put(AppConstants.FIELD.SN, sn);
        map.put(AppConstants.FIELD.PASSWD, psw);
        invoke(mChildRest.openRedPacket(map), new Callback<Object>() {
            @Override
            public void onResponse(Object data, Paginated paginated,Object extraData) {
                super.onResponse(data, paginated,extraData);
                if (type == 2) {
                    if (isnotNull() && mLifecycle.get() instanceof ActionPacketView.RedPacketView) {
                        ((ActionPacketView.RedPacketView) mLifecycle.get()).doOpenSuccess();
                    }
                } else {
                    if (isnotNull() && mLifecycle.get() instanceof ActionPacketView.RedPacketView) {
                        ((ActionPacketView.RedPacketView) mLifecycle.get()).doingOpen();
                    }
                    //开始进行三次检测红包打开状态
                    mViewTick = 3;
                    Message message = handler.obtainMessage();
                    message.what = OpenPacketActivity.VIEW_OPEN_STATE;
                    Bundle bundle = new Bundle();
                    bundle.putString(AppConstants.FIELD.SN, sn);
                    bundle.putString(AppConstants.FIELD.PASSWD, psw);
                    message.setData(bundle);
                    handler.sendMessageDelayed(message, 2500);
                }
            }
        });
    }

    private long timeOutCount = 0;

    public long getTimeOutCount() {
        return timeOutCount;
    }

    protected Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != msg)
                switch (msg.what) {
                    case OpenPacketActivity.COUNT_TIME:
                        timeOutCount -= 1000;
                        if (isnotNull()) {
                            if (timeOutCount >= 0) {
                                ((ActionPacketView.PacketTimeAction) mLifecycle.get()).onTimeCount(timeOutCount);
                                if (handler != null) {
                                    handler.sendEmptyMessageDelayed(OpenPacketActivity.COUNT_TIME, 1000);
                                }
                            } else {
                                ((ActionPacketView.PacketTimeAction) mLifecycle.get()).onTimeCount(-1);
                            }
                        }
                        break;
                    case OpenPacketActivity.PARSE_EEROR:
                        if (isnotNull()) {
                            ((ActionPacketView.PacketTimeAction) mLifecycle.get()).onParseError();
                        }
                        break;
                    case OpenPacketActivity.COUNT_AD_TIME:
                        mTick--;
                        if (mTick >= 0 && isnotNull()) {
                            ((ActionPacketView.RedPacketAction) mLifecycle.get()).updateCloseView(mTick);
                            handler.sendEmptyMessageDelayed(OpenPacketActivity.COUNT_AD_TIME, 1600);
                        }
                        break;
                    case OpenPacketActivity.VIEW_OPEN_STATE:
                        if (mViewTick-- >= 0) {
                            checkRedSnState(msg);
                        }
                        break;
                    case OpenPacketActivity.INVALID_CORRENT:
                        if (mTick == AppConstants.DEFAULT_AD_TIME) {
                            notifyCloseTextChange();
                        }
                        break;
                    default:
                        break;
                }
        }
    };

    private void checkRedSnState(Message msg) {
        String sn = msg.getData().getString(AppConstants.FIELD.SN);
        if (!StringUtils.isEmpty(sn)) {
            Map<String, Object> params = new HashMap<>();
            params.put(AppConstants.FIELD.SN, sn);
            invoke(mChildRest.checkRedSnOpenState(params), new Callback<Map>() {
                @Override
                public void onResponse(Map data, Paginated paginated,Object extraData) {
                    super.onResponse(data, paginated,extraData);
                    if (isnotNull() && mLifecycle.get() instanceof ActionPacketView.RedPacketView) {
                        mViewTick = 0;
                        ((ActionPacketView.RedPacketView) mLifecycle.get()).doOpenSuccess();
                        handler.removeMessages(OpenPacketActivity.VIEW_OPEN_STATE);//停止所有的检测
                    }
                }
            });
            Message message = handler.obtainMessage();
            message.what = OpenPacketActivity.VIEW_OPEN_STATE;
            message.setData(msg.getData());
            handler.sendMessageDelayed(message, 2500);
        }
    }

    public int getmTick() {
        return mTick;
    }

    public void getTimeCount(String createdAt) {
        try {
            long lntimeout = System.currentTimeMillis() - DateUtil.stringToLong(createdAt, "yyyy-MM-dd hh:mm:ss") * 1000;
            timeOutCount = AppConstants.PACKET_TIME_OUT - lntimeout;
            handler.removeMessages(OpenPacketActivity.COUNT_TIME);
            handler.sendEmptyMessage(OpenPacketActivity.COUNT_TIME);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                timeOutCount = AppConstants.PACKET_TIME_OUT - (System.currentTimeMillis() - Long.parseLong(createdAt));
                handler.removeMessages(OpenPacketActivity.COUNT_TIME);
                handler.sendEmptyMessage(OpenPacketActivity.COUNT_TIME);
            } catch (Exception e2) {
                e2.printStackTrace();
                handler.removeMessages(OpenPacketActivity.PARSE_EEROR);
                handler.sendEmptyMessage(OpenPacketActivity.PARSE_EEROR);
            }
        }
    }

    public void stopHandleMessage() {
        handler.removeMessages(OpenPacketActivity.COUNT_TIME);
    }

    public boolean isOnce = true;

    public synchronized void notifyCloseTextChange() {
        if (isOnce) {
            F.w("requestPageClose once");
            isOnce = false;
            handler.removeMessages(OpenPacketActivity.COUNT_AD_TIME);
            handler.sendEmptyMessageDelayed(OpenPacketActivity.COUNT_AD_TIME, 2000);
        }
    }

    public void notifyInvalidCorrent() {
        handler.removeMessages(OpenPacketActivity.INVALID_CORRENT);
        handler.sendEmptyMessage(OpenPacketActivity.INVALID_CORRENT);
    }
}
